package com.darren.archive.interceptor;

import com.darren.framework.entity.BaseEntity;
import com.darren.framework.shiro.ShiroUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import java.io.Serializable;

public class HibernateInterceptor extends EmptyInterceptor {

    private static final long serialVersionUID = -8597658125309889388L;

    protected Logger logger = LogManager.getLogger(getClass());

    /*
     * entity - POJO对象
     * id - POJO对象的主键
     * state - POJO对象的每一个属性所组成的集合(除了ID)
     * propertyNames - POJO对象的每一个属性名字组成的集合(除了ID)
     * types - POJO对象的每一个属性类型所对应的Hibernate类型组成的集合(除了ID)
     */
    @Override
    public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        if (entity instanceof BaseEntity) {
            Long userId = ShiroUtil.getUserId();
            BaseEntity record = (BaseEntity) entity;
            if (record != null && record.getId() != null) {
                record.setCreateBy(userId);
            }
        }
        return super.onSave(entity, id, state, propertyNames, types);
    }

    /* (non-Javadoc)
     * @see org.hibernate.EmptyInterceptor#onFlushDirty(java.lang.Object, java.io.Serializable, java.lang.Object[], java.lang.Object[], java.lang.String[], org.hibernate.type.Type[])
     */

    /**
     * 可以在这里添加修改人
     *
     * @param entity
     * @param id
     * @param currentState
     * @param previousState
     * @param propertyNames
     * @param types
     * @return
     */
    @Override
    public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
        if (entity instanceof BaseEntity) {
            Long userId = ShiroUtil.getUserId();
            BaseEntity record = (BaseEntity) entity;
            if (record != null && record.getId() != null) {
                record.setUpdateBy(userId);
            }
        }
        return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
    }


}
